#pragma once

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <memory>
#include <string>
#include <functional>
#include <unordered_map>

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

// HTTP请求处理器类型
using RequestHandler = std::function<void(http::request<http::string_body>&, http::response<http::string_body>&)>;

// HTTP服务器类
class HttpServer {
public:
    HttpServer(const std::string& address, unsigned short port, int threads = 1);
    ~HttpServer();

    // 启动服务器
    void run();
    
    // 停止服务器
    void stop();
    
    // 注册路由处理器
    void addRoute(const std::string& method, const std::string& path, RequestHandler handler);
    
    // 设置默认处理器
    void setDefaultHandler(RequestHandler handler);

private:
    // 接受连接
    void doAccept();
    
    // 处理连接
    void handleConnection(std::shared_ptr<beast::tcp_stream> stream);
    
    // 处理请求
    void handleRequest(http::request<http::string_body>& req, http::response<http::string_body>& res);
    
    // 发送响应
    void sendResponse(std::shared_ptr<beast::tcp_stream> stream, http::response<http::string_body>& res);

    // 成员变量
    net::io_context ioc_;
    tcp::acceptor acceptor_;
    std::string address_;
    unsigned short port_;
    int threads_;
    bool running_;
    
    // 路由表
    std::unordered_map<std::string, std::unordered_map<std::string, RequestHandler>> routes_;
    RequestHandler defaultHandler_;
private:    
    // 处理器
    void defaultRequestHandler(http::request<http::string_body>& req, http::response<http::string_body>& res);
    void onGetTest(http::request<http::string_body>& req, http::response<http::string_body>& res);
};